<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>节流</title>
	<style>
		h3{	
			width: 300px; 
			height: 300px; 
			background: #afa;
		}
	</style>
</head>
<body>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<h3>节流</h3>
	<script type="text/javascript">
		// 节流 当用户一直按住滚轮不放时，也能每间隔delay执行一次fn
		function throttle(fn, delay) {
			var valid = true;
			return function() {
				// valid 为true 不会执行
				if(!valid){
					return false;
				}
				//valid为false时，开始执行
				// 每delay的时间 并且执行时valid改为true, 执行一次 fn(),
				valid = false;
				setTimeout(function(){
					fn();
					valid = true;
				},delay)
			}
		}
		window.onscroll = throttle(showTop,1000);
		function showTop() {
			// console.log(111111);
			var scrolltop = document.documentElement.scrollTop;
			console.log( '滚动条位置：' + scrolltop);
		}
	</script>
	
</body>
</html>